import { defineStore } from 'pinia';
import * as Cesium from 'cesium';
import Dialog from "@/utils/clickopen/dialog";
import { useScaleStore } from "@/stores/scaleStore";

export const useFengmianStore = defineStore('fengmian', {
  state: () => ({
    viewer: null,
    fengmianData: null,
    isFrontVisible: false,
    isBoundaryVisible: false,
    frontPrimitives: null, // 改为单个 PolylineCollection
    boundaryPrimitives: [],
    handler: null,
    dialogs: null,
    styles: {
      frontSegments: {
        color: Cesium.Color.RED.withAlpha(0.8),
        width: 5,
        height: 110 // 新增高度配置
      },
      boundaryPolygons: {
        color: Cesium.Color.YELLOW.withAlpha(0.5),
        height: 0,
        extrudedHeight: 110
      }
    },
    pickTolerance: 10
  }),
  actions: {
    setViewer(viewer) {
      this.viewer = viewer;
    },

    setFengmianData(data) {
      this.fengmianData = data;
      if (this.isFrontVisible) this.renderFrontSegments();
      if (this.isBoundaryVisible) this.renderBoundaryPolygons();
    },

    renderFrontSegments() {
      this.clearFrontSegments();
      
      if (!this.fengmianData?.frontal_axis_points?.length) return;

      // 创建单个 PolylineCollection 来管理所有线段
      this.frontPrimitives = new Cesium.PolylineCollection();
      
      this.fengmianData.frontal_axis_points.forEach((segment, index) => {
        // 使用 fromDegreesArrayHeights 设置高度
        const positions = Cesium.Cartesian3.fromDegreesArrayHeights([
          segment.start.lon, segment.start.lat, this.styles.frontSegments.height,
          segment.end.lon, segment.end.lat, this.styles.frontSegments.height
        ]);
        
        const polyline = this.frontPrimitives.add({
          positions: positions,
          width: this.styles.frontSegments.width,
          material: new Cesium.Material({
            fabric: {
              type: 'Color',
              uniforms: { color: this.styles.frontSegments.color }
            }
          }),
          id: `front-${index}` // 使用 id 标识每条线段
        });
        
        // 存储额外信息
        polyline.segmentIndex = index;
      });
      
      this.viewer.scene.primitives.add(this.frontPrimitives);
      this.addClickHandler();
    },

    renderBoundaryPolygons() {
      this.clearBoundaryPolygons();
      
      if (!this.fengmianData?.daily_boundaries?.length) return;
    
      this.boundaryPrimitives = this.fengmianData.daily_boundaries.map((polygonArray, index) => {
        const coordinates = [];
        for (let i = 0; i < polygonArray.length; i += 2) {
          coordinates.push([polygonArray[i], polygonArray[i + 1]]);
        }
        
        const primitive = new Cesium.Primitive({
          appearance: new Cesium.MaterialAppearance({
            material: new Cesium.Material({
              fabric: {
                type: 'Color',
                uniforms: { color: this.styles.boundaryPolygons.color }
              }
            }),
            translucent: this.styles.boundaryPolygons.color.alpha < 1.0
          }),
          geometryInstances: new Cesium.GeometryInstance({
            geometry: new Cesium.PolygonGeometry({
              polygonHierarchy: new Cesium.PolygonHierarchy(
                Cesium.Cartesian3.fromDegreesArray(coordinates.flat())
              ),
              height: this.styles.boundaryPolygons.height,
              extrudedHeight: 100,
            }),
            id: `boundary-${index}`
          })
        });
        
        primitive.boundaryIndex = index;
        this.viewer.scene.primitives.add(primitive);
        return primitive;
      });

      this.addClickHandler();
    },

    addClickHandler() {
      if (!this.handler) {
        this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.handler.setInputAction((click) => {
          const scaleStore = useScaleStore();
          const scale = scaleStore.currentScale || 1;
          
          const adjustedPosition = new Cesium.Cartesian2(
            click.position.x / scale,
            click.position.y / scale
          );
          
          // 1. 首先尝试标准拾取
          let pickedObject = this.viewer.scene.pick(adjustedPosition);
          
          // 2. 如果没有拾取到，尝试扩大拾取范围
          if (!Cesium.defined(pickedObject)) {
            // 创建一个拾取矩形区域
            const pickRectangle = new Cesium.BoundingRectangle(
              adjustedPosition.x - this.pickTolerance,
              adjustedPosition.y - this.pickTolerance,
              this.pickTolerance * 2,
              this.pickTolerance * 2
            );
            
            // 获取矩形区域内的所有图元
            const pickedObjects = this.viewer.scene.drillPickFromRectangle(pickRectangle);
            
            // 查找锋面线段或边界多边形
            for (const obj of pickedObjects) {
              if (obj.id && obj.id.startsWith('front-')) {
                pickedObject = obj;
                break;
              } else if (obj.primitive && obj.primitive.boundaryIndex !== undefined) {
                pickedObject = obj;
                break;
              }
            }
          }
          
          const ray = this.viewer.camera.getPickRay(adjustedPosition);
          const cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);
          
          if (Cesium.defined(pickedObject)) {
            let title, content;
            
            // 处理线段点击
            if (pickedObject.id && pickedObject.id.startsWith('front-')) {
              const index = parseInt(pickedObject.id.split('-')[1]);
              const length = this.fengmianData.front_lengths[index].toFixed(3);
              const area = this.fengmianData.front_areas?.[index]?.toFixed(3) ?? "无数据";
              const strength = this.fengmianData.front_strengths?.[index]?.toFixed(3) ?? "无数据";
              
              title = "锋面信息";
              content = {
                title1: "锋轴线长：",
                title2: "锋区面积：",
                title3: "锋区强度：",
                content: `${length} km`,
                content2: `${area} km²`,
                content3: `${strength} ℃/km`
              };
            } 
            // 处理边界多边形点击
            // else if (pickedObject.primitive && pickedObject.primitive.boundaryIndex !== undefined) {
            //   const index = pickedObject.primitive.boundaryIndex;
            //   // 添加边界多边形的信息显示逻辑
            //   title = "边界信息";
            //   content = {
            //     title1: "边界区域：",
            //     content: `边界 ${index + 1}`
            //   };
            // }
            
            if (title && content) {
              const opts = {
                viewer: this.viewer,
                position: { _value: cartesian },
                title: title,
                ...content
              };
              
              if (this.dialogs) {
                this.dialogs.windowClose();
              }
              this.dialogs = new Dialog(opts);
            }
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      }
    },

    calculateDistance(point1, point2) {
      const cartesian1 = Cesium.Cartesian3.fromDegrees(point1.lon, point1.lat);
      const cartesian2 = Cesium.Cartesian3.fromDegrees(point2.lon, point2.lat);
      return Cesium.Cartesian3.distance(cartesian1, cartesian2) / 1000;
    },

    updateStyle(target, style) {
      if (target === 'frontSegments') {
        this.styles.frontSegments = { ...this.styles.frontSegments, ...style };
        if (this.isFrontVisible) this.renderFrontSegments();
      } else if (target === 'boundaryPolygons') {
        this.styles.boundaryPolygons = { ...this.styles.boundaryPolygons, ...style };
        if (this.isBoundaryVisible) this.renderBoundaryPolygons();
      }
    },

    clearFrontSegments() {
      if (this.frontPrimitives) {
        this.viewer.scene.primitives.remove(this.frontPrimitives);
        this.frontPrimitives = null;
      }
    },

    clearBoundaryPolygons() {
      this.boundaryPrimitives.forEach(primitive => {
        this.viewer.scene.primitives.remove(primitive);
      });
      this.boundaryPrimitives = [];
    },

    toggleVisibility(target) {
      if (target === 'frontSegments') {
        this.isFrontVisible = !this.isFrontVisible;
        this.isFrontVisible ? this.renderFrontSegments() : this.clearFrontSegments();
      } else if (target === 'boundaryPolygons') {
        this.isBoundaryVisible = !this.isBoundaryVisible;
        this.isBoundaryVisible ? this.renderBoundaryPolygons() : this.clearBoundaryPolygons();
      }
      
      if (!this.isFrontVisible && !this.isBoundaryVisible && this.handler) {
        this.handler.destroy();
        this.handler = null;
      }
      
      if (this.dialogs && (!this.isFrontVisible || !this.isBoundaryVisible)) {
        this.dialogs.windowClose();
      }
    }
  }
});